const app = getApp();
var socketStatus = 'closed';    // 标识是否开启socket
var sockTimer = 0;
var socketMsgQueue = null;
var webSocket = {
  lockReconnect:false,
  limit:0,
  timer:0,
  // 打开socket信道
  openSocket() {
      // console.log(app.globalData.deviceCode,"55555")
      // socketMsgQueue = app.globalData.deviceCode;
      socketMsgQueue ="579851534952";
      let that = this;
      wx.connectSocket({
        url: 'wss://wss.renbojiaoyu.cn', // 如果使用http协议，url的开头应该是'ws'，是https协议 wss
      })
  },

  // 收到消息回调
  onSocketMessageCallback: function(msg) {
 
  },
  // 关闭信道
  closeSocket() {
    if (socketStatus === 'connected') {
      clearInterval(sockTimer);
      // 关闭 WebSocket 连接
      wx.closeSocket({
        success: (res) => {
          console.log("关闭 WebSocket 连接" , res);
          socketStatus = 'closed';
          
        }
      })
    }
  },

  //发送消息函数
  sendSocketMessage(msg) {
    if (socketStatus === 'connected') {
      // console.log("ffffff",msg)
      wx.sendSocketMessage({
        data: msg
      })
    } else {
      socketMsgQueue = msg
    }
  },

  //断线重连接
  reconnect(){
    let that = this;
    clearInterval(sockTimer);

    if(this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer);
    if(this.limit < 3){
      this.timer = setTimeout(()=>{
        that.openSocket();
        that.lockReconnect = false;
      },5000)
      this.limit=this.limit + 1;
    }
  },

}
 
// 监听WebSocket连接打开事件。callback 回调函数
wx.onSocketOpen(res=>{
  console.log('WebSocket 已连接', res,socketMsgQueue)
  socketStatus = 'connected'; // 标记打开
  clearInterval(sockTimer)
  sockTimer = setInterval(()=>{
    // console.log("1")
    webSocket.sendSocketMessage(socketMsgQueue)
  },1000)
})
 
// 监听WebSocket错误。
wx.onSocketError(function(res) {
  console.log('WebSocket连接打开失败，请检查！', res)
  clearInterval(sockTimer);
  webSocket.reconnect()

})
 
// 监听WebSocket接受到服务器的消息事件。
wx.onSocketMessage(function(msg) {
  // console.log("【websocket 监听到消息】内容如下：",msg);
  if (typeof msg.data !== 'object') {
    // msg.data = msg.data.replace(/\\"/g, "");
    var jj = JSON.parse(msg.data);
    msg.data = jj;
  }
  
  webSocket.onSocketMessageCallback(msg.data)
  
})
 
// 监听WebSocket关闭。
wx.onSocketClose(function(res) {
  console.log('WebSocket 已断开' , res)
  clearInterval(sockTimer);
  webSocket.reconnect();
})
 
module.exports = webSocket;